<?php

namespace App\Http\Controllers\Admin;

use App\Http\Requests\Admin\JobFair\CreateRequest;
use App\Models\Admin\Recruitment;
use App\Models\Admin\RecruitmentAd;
use App\Models\Admin\RecruitmentImg;
use App\Models\Admin\RecruitmentSignUp;
use Illuminate\Http\Request;
use Style, DB;

class JobFairController extends CommonController{
    /**
     * 设置图片位置 返回json
     * @return \Illuminate\Http\JsonResponse
     */
    public function uploadUrl(){
        $json = preg_replace("/\/\*[\s\S]+?\*\//", "", file_get_contents(app_path() . "/Vendor/Ueditor/config.json"));
        return response()->json(json_decode($json, true));
    }

    /**
     * 上传图片
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function jobFairUpload(Request $request){
        if($request->hasFile('upfile')){
            $file = $request->file('upfile');
            $entension = strtolower($file->getClientOriginalExtension());
            $mimeTye = $file->getMimeType();
            $clientName = $file->getClientOriginalName();//客服端文件名
            $size = $file->getSize();//文件大小

            if($file->isValid()){
                if(!in_array($entension, array('jpg', 'gif', 'png','jpeg','doc','docx','xlsx','xls','pdf','ppt','pptx','rar', 'zip', 'tar','txt'))){

                        return response()->json(['error' => 304, 'info' => "文件类型只能为jpg、gif、png、doc、xls、pdf、ppt、rar、zip、txt！"]);
                }else{
                    $fileurl = date("Ym") . '/';
                    $filename = time() . strtolower(str_random(5)) . '.' . $entension;
                    $request->file('upfile')->move(public_path() . '/upload/recruitmentimg/' . $fileurl, $filename);
                    $data['recruitment_id'] = 0;
                    $data['img_url'] = $fileurl . $filename;
                    $data['img_state'] = 0;
                    $data['img_tag'] = $request->img_tag;
                    if(RecruitmentImg::create($data)){
                        $return = array(
                            "state" => 'SUCCESS',
                            "url" => asset('upload/recruitmentimg/' . $fileurl . $filename),
                            "title" => $clientName,
                            "original" => $clientName,
                            "type" => $mimeTye,
                            "size" => $size
                        );
                        return response()->json($return);
                    }
                }
            }
        }else{
            return response()->json(['error' => 306, 'info' => "没有选择上传图片文件！"]);
        }
    }

    /**
     * 报名列表信息
     * @return mixed
     */
    public function signup(Request $request, $id){
        $input = arrayFilter($request->only(['keyword']));
        $signup = RecruitmentSignUp::where('recruitment_id', $id)
            ->where(function($query) use ($input){
                $keyword = (!empty($input['keyword'])) ? $input['keyword'] : '';
                if(strlen($keyword) > 0){
                    $query->where('company', 'like', '%' . $keyword . '%');
                }
            })
            ->orderBy('created_at', 'asc')
            ->paginate(20);
        //找出这家企业已报名名单
        $recruitment = Recruitment::where('id',$id)->select('to_attend')->first();
        $arr = preg_split('/((\r\n)|(\s+))/Uis',$recruitment->to_attend);
        $arr = array_values(array_filter($arr));
        //对每家企业进行标记，看是否存在里面了
        foreach($signup as $key => $val){
            if(in_array($val['company'],$arr)){
                $signup[$key]['haved'] = '已通过';
            }else{
                $signup[$key]['haved'] = '待审核';
            }
        }
        return Style::view('admin.jobfair.signup', compact('signup', 'recruitment', 'id'));
    }

    /**
     * 报名设置通过
     * @return mixed
     */
    public function signUpOk(Request $request, $id){
        $signup = RecruitmentSignUp::where('id',$request->selected_id)
            ->select('company')
            ->first();
        $recruitment = Recruitment::where('id',$id)->select('to_attend')->first();
        $arr = preg_split('/((\r\n)|(\s+))/Uis',$recruitment->to_attend);
        $arr = array_values(array_filter($arr));
        if(!in_array($signup->company,$arr)){
            $arr[] = $signup->company;
        }
        $str_to_attend = implode("\r\n",$arr);
        $result = Recruitment::where('id',$id)->update(['to_attend'=>$str_to_attend]);
        if($result){
            return response()->json(['status' => 0, 'msg' => '参展企业添加成功！']);
        }else{
            return response()->json(['status' => 1, 'msg' => '参展企业添加失败，请稍后重试！']);
        }
    }

    /**
     * 批量删除职位
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function signUpBatchOk(Request $request, $id){
        $signup = RecruitmentSignUp::where('recruitment_id', $id)
            ->whereIn('id',$request->selected_id)
            ->select('company')
            ->orderBy('created_at', 'asc')
            ->paginate(20);
        $recruitment = Recruitment::where('id',$id)->select('to_attend')->first();
        $arr = preg_split('/((\r\n)|(\s+))/Uis',$recruitment->to_attend);
        $arr = array_values(array_filter($arr));
        foreach($signup as $key => $val){
            if(!in_array($val['company'],$arr)){
                $arr[] = $val['company'];
            }
        }
        $str_to_attend = implode("\r\n",$arr);
        Recruitment::where('id',$id)->update(['to_attend'=>$str_to_attend]);
        flash('批量添加参展企业成功！', 'success');
        return redirect()->back();
    }

    /**
     * 显示招聘会
     * @return mixed
     */
    public function index(Request $request){
        $input = arrayFilter($request->only(['keyword', 'recruitment_type']));
        $recruitment = Recruitment::
        where(function($query) use ($input){
            $keyword = (!empty($input['keyword'])) ? $input['keyword'] : '';
            if(strlen($keyword) > 0){
                $query->where('job_title', 'like', '%' . $keyword . '%');
            }
        })->where(function($query) use ($input){
            $recruitment_type = (!empty($input['recruitment_type'])) ? $input['recruitment_type'] : '';
            if(strlen($recruitment_type) > 0){
                $query->where('recruitment_type', $recruitment_type);
            }
        })
            ->orderBy('hold_time', 'desc')
            ->paginate(20);
        return Style::view('admin.jobfair.index', compact('recruitment'));
    }

    /**
     * 添加招聘会
     * @return mixed
     */
    public function create(){
        $strRandom = str_random(40);
        return Style::view('admin.jobfair.create', compact('strRandom'));
    }

    /**
     * 添加招聘会提交
     * @param CreateRequest $request
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    public function store(CreateRequest $request){
        $input = $request->only(['job_title', 'hold_time', 'hold_pm', 'hold_unit', 'hold_address', 'phone',
            'exhibition', 'recruitment_type', 'longitude', 'latitude', 'to_attend', 'job_details']);
        $input['created_at'] = date('Y-m-d H:i:s', time());
        $input['updated_at'] = date('Y-m-d H:i:s', time());
        $id = Recruitment::insertGetId($input);
        if($id){
            $this->delImg($id, $request);
            flash('添加招聘会管理成功', 'success');
            return redirect('admin/job_fair');
        }else{
            return back()->with('errors', '添加招聘会管理失败，请稍后重试！');
        }
    }

    /**
     * @param $id
     */
    public function show($id){
    }

    /**
     * 编辑招聘会
     * @param $id
     * @return mixed
     */
    public function edit($id){
        $recruitment = Recruitment::where('id', $id)->first();
        $recruitmentImg = RecruitmentImg::where('recruitment_id', $id)->orderBy('created_at', 'desc')->first(['img_tag']);
        $recruitment->img_tag = (!empty($recruitmentImg)) ? $recruitmentImg->img_tag : str_random(40);
        return Style::view('admin.jobfair.edit', compact('recruitment'));
    }


    /**
     * 更新招聘会
     * @param CreateRequest $request
     * @param $id
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    public function update(CreateRequest $request, $id){
        $input = $request->only(['job_title', 'hold_time', 'hold_pm', 'hold_unit', 'hold_address', 'phone',
            'exhibition', 'recruitment_type', 'longitude', 'latitude', 'to_attend', 'job_details']);
        $result = Recruitment::where('id', $id)->update($input);
        if($result){
            $this->delImg($id, $request);
            flash('更新招聘会管理成功', 'success');
            return redirect('admin/job_fair');
        }else{
            return back()->with('errors', '添加招聘会管理失败，请稍后重试！');
        }
    }

    /**
     * 删除招聘会
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function destroy($id){
        $result = Recruitment::where('id', $id)->delete();
        if($result){
            //删除多余的图片
            $newRecruitmentImg = RecruitmentImg::where('recruitment_id', $id)->get();
            if(!empty($newRecruitmentImg)){
                RecruitmentImg::where('recruitment_id', $id)->delete();
                foreach($newRecruitmentImg as $v){
                    @unlink(public_path() . '/upload/recruitmentimg/' . $v->img_url);
                }
            }
            return response()->json(['status' => 0, 'msg' => '删除招聘会管理成功！']);
        }else{
            return response()->json(['status' => 1, 'msg' => '删除招聘会管理失败，请稍后重试！']);
        }
    }


    /**
     * 根据跟踪标记删除图片
     * @param $id
     * @param $request
     */
    function delImg($id, $request){
        //根据跟踪标记取出招聘会图片表里面的图片
        $recruitmentImg = RecruitmentImg::select('id', 'recruitment_id', 'img_url')->where('img_tag', $request->img_tag)->get();
        if(!empty($recruitmentImg)){
            $recruitmentImgId = [];
            /*获取招聘会详情取出图片*/
            $job_details = $request->job_details;
            preg_match_all('/<img\s+src=("|\')(.*)("|\')(\s+title(.*))?>/Uis', $job_details, $arr);
            if(count($arr[2]) > 0){
                foreach($arr[2] as $v){
                    foreach($recruitmentImg as $vv){
                        if(stristr($vv->img_url, basename($v))){
                            $recruitmentImgId[] = $vv->id;
                            break;
                        }
                    }
                }
            }
            //更新招聘会图片
            if(count($recruitmentImgId) > 0){
                RecruitmentImg::whereIn('id', $recruitmentImgId)->update(['recruitment_id' => $id, 'img_state' => 1]);
            }
            //删除多余的图片
            $newRecruitmentImg = RecruitmentImg::where('img_tag', $request->img_tag)->whereNotIn('id', $recruitmentImgId)->get();
            if(!empty($newRecruitmentImg)){
                RecruitmentImg::where('img_tag', $request->img_tag)->whereNotIn('id', $recruitmentImgId)->delete();
                foreach($newRecruitmentImg as $v){
                    @unlink(public_path() . '/upload/recruitmentimg/' . $v->img_url);
                }
            }
        }
    }

    //-------------------------------------------------------------------------------------------------------------------------------------------

    /**
     * 招聘会设置
     * @return mixed
     */
    public function jobFairPic(){
        $recruitmentad = RecruitmentAd::select('pic', 'sign', 'id')->first();
        $recruitmentPic = (!empty($recruitmentad) && !empty($recruitmentad->pic)) ? '/upload/recruitmentad/' . $recruitmentad->pic :
            '/default/images/personal/null.jpg';
        return Style::view("admin.jobfair.jobFairPic", compact('recruitmentad', 'recruitmentPic'));
    }

    /**
     * 上传招聘会图片
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function uploadPic(Request $request){
        if($request->hasFile('file')){
            $file = $request->file('file');
            $entension = strtolower($file->getClientOriginalExtension());
            $clientName = $file->getClientOriginalName();//客服端文件名
            if($file->isValid()){
                if(!in_array($entension, array('gif', 'jpg', 'jpeg', 'bmp', 'png'))){
                    return response()->json(['error' => 304, 'info' => "文件类型只能为jpg、gif、png！"]);
                }else{
                    $recruitmentad = RecruitmentAd::select('pic', 'sign', 'id')->first();
                    $fileurl = date("Ym") . '/';
                    $filename = time() . strtolower(str_random(5)) . '.' . $entension;
                    $request->file('file')->move(public_path() . '/upload/recruitmentad/' . $fileurl, $filename);
                    if(empty($recruitmentad)){
                        $input['sign'] = 'jobfair';
                        $input['pic'] = $fileurl . $filename;
                        RecruitmentAd::create($input);
                    }else{
                        @unlink(public_path() . '/upload/recruitmentad/' . $recruitmentad->pic);
                        $recruitmentad->pic = $fileurl . $filename;
                        $recruitmentad->save();
                    }
                    return response()->json(['status' => 200, 'url' => asset('upload/recruitmentad/' . $fileurl . $filename)]);
                }
            }
        }else{
            return response()->json(['error' => 306, 'info' => "没有选择上传图片文件,或者文件过大！"]);
        }
    }

    /**
     * 招聘会照片删除
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function delPic(Request $request){
        if(empty($request->id)){
            return response()->json(['status' => 0, 'msg' => "图片已经被删除,请先上传图片！"]);
        }else{
            $recruitmentad = RecruitmentAd::where('id', $request->id)->first(['pic', 'sign', 'id']);
            if(!empty($recruitmentad->pic)){
                @unlink(public_path() . '/upload/recruitmentad/' . $recruitmentad->pic);
                $recruitmentad->pic = '';
                $recruitmentad->save();
                return response()->json(['status' => 1, 'msg' => "删除成功"]);
            }else{
                return response()->json(['status' => 0, 'msg' => "图片已经被删除,请先上传图片"]);
            }
        }
    }
}